<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use think\facade\Db;
class FreightLogic extends BasicLogic
{

    /**
     * @desc    获取预估重量和预估运费
     * @date    2024/09/05
     * @author  luckyXiong
     */
    public function get_estimate_fee($order_id){
        if(!$order_id)  return '订单id不能为空!';
        $info    = Db::name('order_info')->field('id,order_id,sku,spu,quantity')->where('order_id',$order_id)->select()->toArray();
        if(!$info)  return '暂无数据!';
        foreach($info as $v){
            if(!$v['sku']) continue;
            $sku_info = self::get_shopify_spus($v['sku'],$v['quantity']);
            if(is_array($sku_info)){
                $sku  = $sku_info['string'];
                $type = $sku_info['type'];
            }else{
                $sku   = $sku_info;
                $type  = 1;
            }
            $temp = [
                'id'              =>$v['id'],
                'order_id'        =>$v['order_id'],
                'sku'             =>$sku,
                'num'             =>$v['quantity']*$type,
                'spu'             =>$v['spu'],
            ];
            $arr[] =$temp;
        }
        foreach($arr as $k=>$v){
            $sum = 1;
            if(strpos($v['sku'],',')){
                $arr_sku = explode(',',$v['sku']);
                $current = current($arr_sku);

                if(preg_match('/.*-(\d+)$/', $current, $matches)){
                    $sum = $matches[1] > 20 ? 1 : $matches[1];
                }
                $sum = $sum*count($arr_sku);
                $arr[$k]['num'] = $sum;
            }else{
                if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                    $single_sku = Db::name('order_info')->where(['id'=>$v['id']])->value('sku');
                    if(preg_match('/.*-(\d+)$/', $single_sku, $matches)){
                        $sum = $matches[1];
                    }else{
                        $sum =1;
                    }
                }
                $sum = $sum > 20 ? 1 : $sum;
                $arr[$k]['num'] = $v['num']*$sum;
             }
        }

        foreach($arr as $k=>$v){
                $weight_info       = self::get_weight($v['spu']);
                $arr[$k]['weight'] = $v['num']*$weight_info;
        }

        $weight_info = array_sum(array_column($arr, 'weight'));
        $num_info    = array_sum(array_column($arr, 'num'));
        //update  2024-09-09 获取
        $fee_info     = Db::name('product_sku_freight')->where(['id'=>1])->find();
        $fee          = ($weight_info/1000) * $fee_info['single_price']+$fee_info['register_fee'];
        $fee          = getRes($fee);
        return  [
            'weight'   =>$weight_info,
            'fee'      =>$fee,
            'num'      =>$num_info,
        ];
    }



    /**
     * @desc   获取预估重量
     * @author luckyXiong
     * @date   2024-09-05
     */
    private function get_weight($spu){
        $weight = Db::name('product_spu_weight')->where(['spu'=>$spu])->value('weight');
        if(!$weight){
            $type = Db::name('product')->where(['spu'=>$spu])->value('product_attr_type');
            switch($type) {
                case "1100":
                    $weight = '130';
                    break;
                case "1200":
                    $weight = '190';
                    break;
                case "1300":
                    $weight = '200';
                    break;
                case "1400":
                    $weight = '200';
                    break;
                case "1500":
                    $weight = '200';
                    break;
                default:
                    $weight = '200';
                    break;
            }
        }
        return  $weight;
    }



    /**
     * @desc   获取预估重量
     * @author luckyXiong
     * @date   2024-09-05
     */
    private function get_sku_num($list=[],$order_id=''){
        foreach($list as $v){
            $sku  = self::get_seller_sku($v);
            if($sku==2) continue;
            $temp = [
                'sku'             =>$sku,
                'num'             =>1,
                'order_id'        =>$order_id,
            ];
            $arr[] =$temp;
        }

        $skus = [];
        $num  = 0;
        $arr  = self::get_unique_sku($arr);
        foreach($arr as $v){
            $num+= $v['num'];
            if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                $skus[] = $v['sku'];
            }else{
                $skus[] = $v['num'] > 1 ? $v['sku'].'-'.$v['num'] : $v['sku'];
            }
        }
        return $skus;
    }



    public function get_seller_sku($sku,$num=1){
        try{
            return get_shopify_spu($sku,$num);
        }catch (\Exception $e) {
            return 2;
        }

    }


    /**
     * @desc  get_unique_sku
     * @author xx
     * @date 2024-09-05
     */
    public function get_unique_sku($orders=[]){
        // 新数组
        $newOrders = [];
        // 循环原始数组，拆分并合并sku，并累加num值
        foreach ($orders as $order) {
            $skus = explode(',', $order['sku']);
            foreach ($skus as $sku) {
                $key = $order['order_id'] . '-' . $sku;

                if (isset($newOrders[$key])) {
                    // 如果已经存在相同订单和SKU的记录，累加num值
                    $newOrders[$key]['num'] += $order['num'];
                } else {
                    // 新的订单和SKU，直接加入新数组
                    $newOrders[$key] =[
                        'order_id' => $order['order_id'],
                        'sku'      => $sku,
                        'num'      => $order['num'],
                    ];
                }
            }
        }
        return  array_values($newOrders);
    }


    public function get_spu_fee(){
        $where= [];
        $order_ids  = [];
        $t1         = microtime(true);
        $list = Db::name('order_achievement')->field('order_id,spu')->whereIn('order_id',$order_ids)->select()->toArray();
        $count = count($list);
        $executedCount =0;
        foreach ($list as $k=>$v){
                echo PHP_EOL ."执行第:" . ($k+1) ."条".PHP_EOL;
                $weight_info = self::get_estimate_fee($v['order_id']);
                $update= [
                    'estimate_freight'    => $weight_info['fee'] ?? '0',
                    'estimate_weight'     => $weight_info['weight'] ?? '0',
                    'quantity_new'        => $weight_info['num'] ?? '0',
                ];
                Db::name('order_achievement')->where('order_id',$v['order_id'])->update($update);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        echo PHP_EOL . "get_spu_fee-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    private function get_shopify_spus($string,$num){
        $parts = explode('+', $string);
        $type  = count($parts);
        //获取spu
        $spu_info   = explode('-', $parts[0]);
        $spu        = $spu_info[0];
        switch($type){
            case 1:
                //查看string 尾部是否有数字
                if (preg_match('/.*-(\d+)$/', $string, $matches)) {
                    return  $string;
                }else{
                    return  $num >1 ? $string.'-'.$num : $string;
                }

            case 2:
                preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
                $color0 = $matches_color0[1];
                preg_match('/^([a-zA-Z]+)/',    $parts[1], $matches_color1);
                $color1 = $matches_color1[1];
                preg_match('/-([a-zA-Z0-9]+)/', $parts[1], $matches_size);
                $size  = $matches_size[1];
                if($num >1){
                    return $spu.'-'.$color0.'-'.$size.'-'.$num.','.$spu.'-'.$color1.'-'.$size.'-'.$num;
                }else{
                    return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size;
                }
            case 3:
                preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
                $color0 = $matches_color0[1];
                $color1 = $parts[1];
                $parts2 = explode("-", $parts[2]);
                $color2 = $parts2[0];
                $size   = $parts2[1];
                if($num >1){
                    return $spu.'-'.$color0.'-'.$size.'-'.$num.','.$spu.'-'.$color1.'-'.$size.'-'.$num.','.$spu.'-'.$color2.'-'.$size.'-'.$num;
                }else{
                    return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size.','.$spu.'-'.$color2.'-'.$size;
                }
            default:
                return [
                    'string' =>$string,
                    'type'   =>$type
                ];

        }
    }


}